#include <config.h>
#include <fonts_manager.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

int GbkFontInit(char *FileName, unsigned int dwFontSize);
int GbkGetFontBitmap(unsigned int dwCode, PT_Bitmap ptBitmap);

static T_FontOpr g_tGbkFontOpr = {
	.name = "gbk",
	.FontInit = GbkFontInit,
	.GetFontBitmap = GbkGetFontBitmap,
};

static int g_iFdHzk;
static unsigned char *g_pucHzkMem;
static unsigned char *g_pucHzkMemEnd;

int GbkFontInit(char *FileName, unsigned int dwFontSize)
{
	struct stat tStat;
	
	if(dwFontSize != 16)
	{
		DEG_PRINTF("HZK can't support %d Font Size\n", dwFontSize);
		return -1;
	}

	g_iFdHzk = open(FileName, O_RDONLY);
	if(g_iFdHzk < 0)
	{
		printf("Can't open hzk\n");
		return -1;
	}

	if(fstat(g_iFdHzk, &tStat))
	{
		DEG_PRINTF("Can't get Hzk stat\n");
		return -1;
	}

	g_pucHzkMem = (unsigned char *)mmap(NULL, tStat.st_size, PROT_READ, MAP_SHARED, g_iFdHzk, 0);
	if(g_pucHzkMem == (unsigned char *)-1)
	{
		DEG_PRINTF("Can't mmap Hzk \n");
		return -1;
	}

	g_pucHzkMemEnd = g_pucHzkMem + tStat.st_size;
	
	return 0;
}

int GbkGetFontBitmap(unsigned int dwCode, PT_Bitmap ptBitmap)
{	
	int iArea;
	int iWhere;
	
	int iPenX = ptBitmap->iCurOriginX;
	int iPenY = ptBitmap->iCurOriginY;


	
	if (dwCode & 0xffff0000)
	{	
		DEG_PRINTF("don't support this code : 0x%x\n", dwCode);
		return -1;
	}

	iArea = (int)(dwCode & 0xff) - 0xA1;
	iWhere = (int)((dwCode>>8) & 0xff) - 0xA1;

	ptBitmap->iXLeft = iPenX;
	ptBitmap->iYTop  = iPenY - 16;
	ptBitmap->iXMax  = iPenX + 16;
	ptBitmap->iYMax  = iPenY;
	ptBitmap->iBpp   = 1;
	ptBitmap->iPitch = 2;
	ptBitmap->pucBuffer = g_pucHzkMem + (iArea*94 + iWhere) * 32;

	if(ptBitmap->pucBuffer >= g_pucHzkMemEnd)
	{
		return -1;;
	}
	ptBitmap->iNextOriginX = iPenX + 16;
	ptBitmap->iNextOriginY = iPenY;

	return 0;
}

int GbkFontRegister(void)
{
	return RegisterFontOpr(&g_tGbkFontOpr);
}

